import { GetCookie } from '@/utils/jscookie'

// var token = localStorage.getItem("_token");
var token = GetCookie("_token");
var userInfo = GetCookie('_userinfo');
// 链接socket地址
var url = "ws://127.0.0.1:8088/chat/chat?_token="+token;

var wsk = new WebSocket(url);

wsk.onopen = function () {
    console.log("wk 连接...ping")
    wsSendMessage()
}

wsk.onclose = function (event) {
    closeWs()
    console.log("WebSocket is closed now." + event);
}

wsk.onerror = function (event) {
    closeWs()
    console.log("WebSocket is closed now." + event);
}

function wsSendMessage () {
    if (userInfo != "") {
        userInfo = JSON.parse(userInfo)
    }
    var message = {
        user_id: userInfo.id,
        cmd: 1,
        content:"ping"
    };
    wsk.send(JSON.stringify(message));
}

function closeWs() {
    wsk.close();
    // clearInterval(timer)
}

export var ws = wsk